import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Device } from './DbModel/device.entity'
import {DeviceDTO} from "./dto/DeviceDTO";
import deviceManager from "./deviceManager";
import ObjectUtil from "./ObjectUtil";

@Injectable()
export class DeviceService {

  constructor(
    @InjectRepository(Device)
    private readonly deviceRepository: Repository<Device>,
  ) {}

  async list() {
    return deviceManager.list();
  }

  addMessage(deviceId: number, message: string) {
    deviceManager.addMessage(deviceId, message);
  }

  async add(dto: DeviceDTO) {
    let device = new Device();
    ObjectUtil.copyProperties(device, dto);
    device = await this.deviceRepository.save(device);
    return deviceManager.publish(device);
  }

  async publishAll() {
    const deviceList = await this.deviceRepository.find();
    for(const device of deviceList) {
      deviceManager.publish(device);
    }

  }

  start(deviceId:number) {
    deviceManager.start(deviceId)
  }

  /**
   * 关闭设备
   * @param deviceId
   */
  shutdown(deviceId:number) {
    deviceManager.shutdown(deviceId);
  }

  /**
   * 删除设备
   * @param deviceId
   */
  async del(deviceId:number) {
    // 关闭设备
    deviceManager.shutdown(deviceId);
    deviceManager.del(deviceId);
    await this.deviceRepository.delete([deviceId]);

  }

  /**
   * 获取设备状态
   * @param deviceId
   */
  getStatus(deviceId:number) {
    // 关闭设备
    return deviceManager.getStatus(deviceId);

  }

  /**
   * 获取设备状态
   * @param deviceId
   */
  getDetail(deviceId:number) {
    // 关闭设备
    return deviceManager.getDetail(deviceId);
  }

}
